<template>
</template>

<script>
import {getToken} from "../../utils/storage";

export default {
  name: "WebSocket",
  data() {
    return {
      websocket: null, // 初始化为 null 避免未定义
      list: [],
      messageData: {
        title: null,
        type: null,
        message: null,
      }
    }
  },
  methods: {
    initWebSocket() {
      const token = getToken();
      //后端地址
      const url = "ws://127.0.0.1:21090/api/book-manage-sys-api/v1.0/webSocket/" + token;
      this.websocket = new WebSocket(url);

      this.websocket.onopen = this.open;
      this.websocket.onerror = this.error;
      this.websocket.onclose = this.close;
      this.websocket.onmessage = this.getMessage;
    },
    close() {
      console.log("socket连接关闭");
    },
    open() {
      console.log("socket连接成功");
    },
    // 收到后端的消息
    getMessage(msg) {

      this.messageData = JSON.parse(msg.data);

      this.$notify({
        title: this.messageData.title,
        message: this.messageData.message,
        type: this.messageData.type,
        duration: 10000,
      });
    },
    error() {
      console.log("连接错误");
    },
    sendMsg() {
      if (this.websocket.readyState === WebSocket.OPEN) {
        this.websocket.send(JSON.stringify(this.messageData));
      }
    },
  },
  mounted() {
    this.initWebSocket();
  },
  destroyed() {
    if (this.websocket) {
      this.websocket.close();
    }
  }
}
</script>
